package serial

import (
	"github.com/project-flogo/core/data/coerce"
)

type Settings struct {
	Port        string  `md:"port" json:"port,omitempty"`
	Baudrate    int     `md:"baudrate" json:"baudrate,omitempty"`
	DataBits    int     `md:"dataBits" json:"dataBits,omitempty"`
	StopBits    float32 `md:"stopBits" json:"stopBits,omitempty"`
	Parity      string  `md:"parity" json:"parity,omitempty"`
	ReadTimeout string  `md:"readTimeout"`
}

type Input struct {
	Data []byte `md:"data"`
}

func (r *Input) ToMap() map[string]interface{} {
	return map[string]interface{}{
		"data": r.Data,
	}
}

func (r *Input) FromMap(values map[string]interface{}) error {
	data, err := coerce.ToBytes(values["data"])
	if err != nil {
		return err
	}
	r.Data = data
	return nil
}

type Output struct {
	Err   string `md:"err"`
	Count int    `md:"count"`
}

func (o *Output) ToMap() map[string]interface{} {
	return map[string]interface{}{
		"err":   o.Err,
		"count": o.Count,
	}
}

func (o *Output) FromMap(values map[string]interface{}) error {
	str, err := coerce.ToString(values["err"])
	if err != nil {
		return err
	}
	o.Err = str

	count, err := coerce.ToInt(values["count"])
	if err != nil {
		return err
	}
	o.Count = count
	return nil
}
